<template>
  <div class="notice-manage">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="公告标题">
          <el-input v-model="searchForm.title" placeholder="请输入公告标题" clearable />
        </el-form-item>
        <el-form-item label="公告类型">
          <el-select v-model="searchForm.type" placeholder="请选择公告类型" clearable>
            <el-option label="系统公告" :value="1" />
            <el-option label="活动公告" :value="2" />
            <el-option label="维护公告" :value="3" />
            <el-option label="安全公告" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" :value="0" />
            <el-option label="已发布" :value="1" />
            <el-option label="已下线" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="searchNotices">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card">
      <el-button type="primary" :icon="Plus" @click="openAddDialog">新增公告</el-button>
      <el-button type="danger" :icon="Delete" @click="batchDelete" :disabled="selectedNotices.length === 0">
        批量删除
      </el-button>
      <el-button type="success" :icon="Top" @click="batchPublish" :disabled="selectedNotices.length === 0">
        批量发布
      </el-button>
    </el-card>

    <!-- 公告列表 -->
    <el-card>
      <el-table
        :data="noticeList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="公告ID" width="80" />
        <el-table-column prop="title" label="公告标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="公告类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getNoticeTypeTag(row.type)">
              {{ getNoticeTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="{ row }">
            <el-tag :type="getPriorityTag(row.priority)">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="views" label="浏览量" width="80" />
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-form-item prop="publishTime" label="发布时间" width="180" />
        <el-table-column prop="expireTime" label="过期时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button 
              type="success" 
              :icon="Top" 
              size="small" 
              @click="publishNotice(row)" 
              v-if="row.status === 0"
            >
              发布
            </el-button>
            <el-button 
              type="warning" 
              :icon="Bottom" 
              size="small" 
              @click="offlineNotice(row)" 
              v-if="row.status === 1"
            >
              下线
            </el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="deleteNotice(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增公告' : '编辑公告'"
      width="800px"
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择公告类型" style="width: 200px">
            <el-option label="系统公告" :value="1" />
            <el-option label="活动公告" :value="2" />
            <el-option label="维护公告" :value="3" />
            <el-option label="安全公告" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 200px">
            <el-option label="低" :value="1" />
            <el-option label="中" :value="2" />
            <el-option label="高" :value="3" />
            <el-option label="紧急" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间" required>
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <quill-editor
              v-model="form.content"
              :options="editorOptions"
              style="height: 300px"
            />
          </div>
        </el-form-item>
        <el-form-item label="附件" prop="attachments">
          <el-upload
            :action="uploadAction"
            :file-list="form.attachments"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            multiple
            :limit="5"
            :on-exceed="handleExceed"
          >
            <el-button type="primary" :icon="Upload">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">只能上传 jpg/png/pdf/doc/docx 文件，且不超过 10MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="0">草稿</el-radio>
            <el-radio :value="1">立即发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveNotice" :loading="saveLoading">
          {{ dialogType === 'add' ? '新增' : '更新' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="公告详情"
      width="800px"
      @close="closeDetailDialog"
    >
      <div class="notice-detail">
        <div class="notice-header">
          <h2>{{ currentNotice.title }}</h2>
          <div class="notice-meta">
            <el-tag :type="getNoticeTypeTag(currentNotice.type)">
              {{ getNoticeTypeLabel(currentNotice.type) }}
            </el-tag>
            <span class="priority">优先级：{{ getPriorityLabel(currentNotice.priority) }}</span>
            <span class="creator">创建人：{{ currentNotice.creator }}</span>
            <span class="create-time">创建时间：{{ currentNotice.createTime }}</span>
          </div>
        </div>
        <div class="notice-content" v-html="currentNotice.content"></div>
        <div v-if="currentNotice.attachments && currentNotice.attachments.length > 0" class="notice-attachments">
          <h4>附件：</h4>
          <el-link 
            v-for="(file, index) in currentNotice.attachments" 
            :key="index"
            :href="file.url" 
            :download="file.name"
            type="primary"
          >
            {{ file.name }}
          </el-link>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh, Top, Bottom, Upload } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  title: '',
  type: '',
  status: '',
  createTime: ''
})

// 公告列表数据
const noticeList = ref([])
const loading = ref(false)
const selectedNotices = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框参数
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref('add')
const saveLoading = ref(false)

// 表单数据
const form = ref({
  id: '',
  title: '',
  type: 1,
  priority: 2,
  content: '',
  publishTime: '',
  expireTime: '',
  status: 0,
  attachments: [],
  timeRange: []
})

// 当前查看的公告
const currentNotice = ref({})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ],
  timeRange: [
    { required: true, message: '请选择生效时间范围', trigger: 'change' }
  ]
}

const formRef = ref()

// 编辑器配置
const editorOptions = {
  theme: 'snow',
  placeholder: '请输入公告内容...',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image', 'video']
    ]
  }
}

// 上传配置
const uploadAction = '/api/upload/notice'

// 模拟数据
const mockNotices = [
  {
    id: 1,
    title: '系统升级通知',
    type: 1,
    priority: 3,
    content: '<p>尊敬的用户：</p><p>为了提供更好的服务，系统将于<strong>2024年2月15日凌晨2:00-4:00</strong>进行升级维护。期间可能无法访问系统，请提前做好准备。</p><p>感谢您的理解与支持！</p>',
    status: 1,
    views: 156,
    creator: '管理员',
    createTime: '2024-01-15 10:30:00',
    publishTime: '2024-01-15 11:00:00',
    expireTime: '2024-02-20 00:00:00',
    attachments: []
  },
  {
    id: 2,
    title: '新春活动公告',
    type: 2,
    priority: 2,
    content: '<p>新春佳节即将到来，为庆祝新春，特推出以下活动：</p><ul><li>新用户注册送好礼</li><li>老用户登录领红包</li><li>邀请好友得奖励</li></ul>',
    status: 1,
    views: 89,
    creator: '运营部',
    createTime: '2024-01-20 14:20:00',
    publishTime: '2024-01-20 15:00:00',
    expireTime: '2024-02-10 00:00:00',
    attachments: []
  },
  {
    id: 3,
    title: '安全提醒',
    type: 4,
    priority: 4,
    content: '<p>近期发现有不法分子冒充系统客服进行诈骗，请提高警惕：</p><ol><li>不要轻信陌生来电</li><li>不要透露账号密码</li><li>有疑问请联系官方客服</li></ol>',
    status: 1,
    views: 234,
    creator: '安全部',
    createTime: '2024-01-25 09:15:00',
    publishTime: '2024-01-25 09:30:00',
    expireTime: '2024-03-25 00:00:00',
    attachments: []
  }
]

// 工具方法
const getNoticeTypeLabel = (type) => {
  const labels = {
    1: '系统公告',
    2: '活动公告',
    3: '维护公告',
    4: '安全公告'
  }
  return labels[type] || '未知'
}

const getNoticeTypeTag = (type) => {
  const tags = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'danger'
  }
  return tags[type] || 'info'
}

const getPriorityLabel = (priority) => {
  const labels = {
    1: '低',
    2: '中',
    3: '高',
    4: '紧急'
  }
  return labels[priority] || '未知'
}

const getPriorityTag = (priority) => {
  const tags = {
    1: 'info',
    2: 'success',
    3: 'warning',
    4: 'danger'
  }
  return tags[priority] || 'info'
}

const getStatusLabel = (status) => {
  const labels = {
    0: '草稿',
    1: '已发布',
    2: '已下线'
  }
  return labels[status] || '未知'
}

const getStatusTag = (status) => {
  const tags = {
    0: 'info',
    1: 'success',
    2: 'danger'
  }
  return tags[status] || 'info'
}

// 加载公告列表
const loadNoticeList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const filteredData = mockNotices.filter(item => {
      const matchTitle = !searchForm.value.title || item.title.includes(searchForm.value.title)
      const matchType = !searchForm.value.type || item.type === searchForm.value.type
      const matchStatus = !searchForm.value.status || item.status === searchForm.value.status
      return matchTitle && matchType && matchStatus
    })
    
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    noticeList.value = filteredData.slice(start, end)
    total.value = filteredData.length
  } catch (error) {
    ElMessage.error('获取公告列表失败')
    console.error('Failed to load notice list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索公告
const searchNotices = () => {
  currentPage.value = 1
  loadNoticeList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    type: '',
    status: '',
    createTime: ''
  }
  currentPage.value = 1
  loadNoticeList()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedNotices.value = val
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  loadNoticeList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadNoticeList()
}

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  form.value = {
    id: '',
    title: '',
    type: 1,
    priority: 2,
    content: '',
    publishTime: '',
    expireTime: '',
    status: 0,
    attachments: [],
    timeRange: []
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row) => {
  form.value = {
    ...row,
    timeRange: [row.publishTime, row.expireTime]
  }
  dialogType.value = 'edit'
  dialogVisible.value = true
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 保存公告
const saveNotice = async () => {
  try {
    await formRef.value.validate()
    saveLoading.value = true
    
    // 设置发布时间和过期时间
    if (form.value.timeRange && form.value.timeRange.length === 2) {
      form.value.publishTime = form.value.timeRange[0]
      form.value.expireTime = form.value.timeRange[1]
    }
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(dialogType.value === 'add' ? '新增公告成功' : '更新公告成功')
    closeDialog()
    loadNoticeList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(dialogType.value === 'add' ? '新增公告失败' : '更新公告失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 发布公告
const publishNotice = async (row) => {
  try {
    await ElMessageBox.confirm('确定要发布该公告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('公告发布成功')
    loadNoticeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('公告发布失败')
    }
  }
}

// 下线公告
const offlineNotice = async (row) => {
  try {
    await ElMessageBox.confirm('确定要下线该公告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('公告下线成功')
    loadNoticeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('公告下线失败')
    }
  }
}

// 删除公告
const deleteNotice = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该公告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('公告删除成功')
    loadNoticeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('公告删除失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedNotices.value.length === 0) {
    ElMessage.warning('请选择要删除的公告')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedNotices.value.length} 个公告吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('批量删除公告成功')
    loadNoticeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除公告失败')
    }
  }
}

// 批量发布
const batchPublish = async () => {
  if (selectedNotices.value.length === 0) {
    ElMessage.warning('请选择要发布的公告')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要发布选中的 ${selectedNotices.value.length} 个公告吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('批量发布公告成功')
    loadNoticeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量发布公告失败')
    }
  }
}

// 查看详情
const viewNoticeDetail = (row) => {
  currentNotice.value = row
  detailDialogVisible.value = true
}

const closeDetailDialog = () => {
  detailDialogVisible.value = false
  currentNotice.value = {}
}

// 文件上传相关
const handleUploadSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    form.value.attachments = fileList.map(f => ({
      name: f.name,
      url: f.response ? f.response.data.url : f.url,
      size: f.size
    }))
  } else {
    ElMessage.error(response.message || '文件上传失败')
  }
}

const handleRemove = (file, fileList) => {
  form.value.attachments = fileList.map(f => ({
    name: f.name,
    url: f.response ? f.response.data.url : f.url,
    size: f.size
  }))
}

const beforeUpload = (file) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
  const isAllowed = allowedTypes.includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isAllowed) {
    ElMessage.error('只能上传 jpg/png/pdf/doc/docx 文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件')
}

// 初始化加载
onMounted(() => {
  loadNoticeList()
})
</script>

<style scoped>
.notice-manage {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.notice-detail {
  padding: 20px;
}

.notice-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.notice-header h2 {
  margin-bottom: 15px;
  color: #303133;
}

.notice-meta {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
  color: #909399;
  font-size: 14px;
}

.notice-content {
  line-height: 1.8;
  color: #606266;
  margin-bottom: 20px;
}

.notice-attachments {
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.notice-attachments h4 {
  margin-bottom: 10px;
  color: #303133;
}

.notice-attachments .el-link {
  display: block;
  margin-bottom: 5px;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
  
  .notice-meta {
    flex-direction: column;
    gap: 10px;
  }
}
</style>